package jsyf.oa.dao.apply;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import jsyf.oa.dao.system.LogsDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

import jsyf.oa.entity.apply.MoneyMainEntity;
import jsyf.oa.idao.BaseDao;
import jsyf.oa.ientity.IBaseEntity;

/**
 * @author GUOQI
 */
@Repository
public class MoneyMainDao extends BaseDao {

    @Autowired
    LogsDao logsDao;

    public MoneyMainDao() {
        super.iBaseEntity = new MoneyMainEntity();
    }

    public MoneyMainEntity getEntityById(String id) {
        return (MoneyMainEntity) super.getIBaseEntityById(id);
    }


    @Override
    public IBaseEntity convertJson2Entity(JSONObject json) {
        return JSON.toJavaObject(json, MoneyMainEntity.class);
    }

    public List<JSONObject> getJSONListByPage(String currentUserId, String condition, Object[] params, int requestPage, int pageSize, String haveRefund) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT ");
        sql.append("ID AS id, ");
        sql.append("TYPE AS type, ");
        sql.append("TITLE AS title, ");
        sql.append("SERIES_NUMBER AS seriesNumber, ");
        sql.append("ORG_NAME AS orgName, ");
        sql.append("REGION_NAME AS regionName, ");
        sql.append("DESCRIPTION AS description, ");
        sql.append("CREATE_USER_ID AS createUserId, ");
        sql.append("CREATE_TIME AS createTime,");
        //sql.append("DATE_FORMAT(CREATE_TIME, '%H:%i %m-%d') AS createTime, ");
        sql.append("PAY_USER_ID AS payUserId, ");
        sql.append("PAY_DATE AS payDate, ");
        sql.append("REMARK AS remark, ");
        sql.append("URGENT_FLAG AS urgentFlag, ");
        sql.append("AUDIT_FLAG AS auditFlag, ");
        sql.append("PAY_REMARK AS payRemark, ");
        sql.append("MONEY AS money, ");
        sql.append("UPDATE_TIME AS updateTime, ");
        sql.append("RETURN_TYPE AS returnType, ");
        sql.append("CREATE_USER_NAME AS createUserName, ");
        sql.append("CURRENT_AUDITOR_ID AS currentAuditorId, ");
        sql.append("CURRENT_AUDITOR_NAME AS currentAuditorName, ");
        sql.append("COMPANY_ID AS companyId, ");
        sql.append("PAY_USER_NAME AS payUserName, ");


        sql.append(" HAVE_REFUND AS haveRefund, ");
        sql.append("ESTIMATED_RETURN_DATE AS estimatedReturnDate, ");
        sql.append("ESTIMATED_RETURN_MONEY AS estimatedReturnMoney, ");
        sql.append("ACTUAL_RETURN_DATE AS actualReturnDate, ");
        sql.append("ACTUAL_RETURN_MONEY AS actualReturnMoney, ");
        sql.append("RETURN_PAYEE_ID AS returnPayeeId, ");
        sql.append("RETURN_PAYEE_NAME AS returnPayeeName, ");
        sql.append("RETURN_PAYEE_ROLE_NAME AS returnPayeeRoleName, ");
        sql.append("HAVE_RETURN_CLEAR AS haveReturnClear, ");
        sql.append("RETURN_REMARK AS returnRemark, ");
        sql.append("REFUND_FLAG AS refundFlag,  ");


        sql.append("(SELECT COUNT(1) FROM V_APL_MONEY_PAYER WHERE fkMoneyId = T_APL_MONEY_MAIN.ID and payerId in(SELECT id FROM V_SYS_USER WHERE departName LIKE '%财务%' OR roleName LIKE '%财务%') AND payerId = '" + currentUserId + "') as canPayFlag, ");
        sql.append("CASE AUDIT_FLAG ");
        // 1 自己的草稿
        sql.append("    WHEN '-1' THEN 1");
        // 2 轮到自己审核的
        sql.append("    WHEN '0' THEN ");
        sql.append("    CASE CURRENT_AUDITOR_ID ");
        sql.append("      WHEN '" + currentUserId + "' THEN 2 ");
        sql.append("      ELSE 5 ");
        sql.append("    END ");
        sql.append("    WHEN '3' THEN ");
        sql.append("    CASE CURRENT_AUDITOR_ID ");
        sql.append("      WHEN '" + currentUserId + "' THEN 3 ");
        sql.append("      ELSE 5 ");
        sql.append("    END ");
        sql.append("    WHEN '4' THEN 4 ");
        sql.append("    WHEN '1' THEN 5 ");
        sql.append("    WHEN '2' THEN 5 ");
        sql.append("    WHEN '5' THEN 5 ");
        sql.append("    WHEN '6' THEN 5 ");
        sql.append("END AS sortNo \n");
        sql.append(",CASE HAVE_REFUND\n" +
                "WHEN '1' THEN\n" +
                "\t(\n" +
                "\t\tCASE REFUND_FLAG\n" +
                "\t\tWHEN '-1' THEN\n" +
                "\t\t\t'2'\n" +
                "\t\tWHEN '0' THEN\n" +
                "\t\t\tCASE CURRENT_AUDITOR_ID\n" +
                "\t\tWHEN '" + currentUserId + "' THEN\n" +
                "\t\t\t'1'\n" +
                "else '3' end\n" +
                "\t\tELSE\n" +
                "\t\t\t'4'\n" +
                "\t\tEND\n" +
                "\t)\n" +
                "ELSE\n" +
                "\t10\n" +
                "END AS refundSortNo");
        // 3 其他状态按时间顺序

//        sql.append("  WHEN '-1' THEN ");
//        sql.append("    CASE CREATE_USER_ID ");
//        sql.append("      WHEN '" + currentUserId + "' THEN 0 ");
//        sql.append("      ELSE 7 ");
//        sql.append("    END ");
//        sql.append("  WHEN '0' THEN ");
//        sql.append("    CASE CURRENT_AUDITOR_ID ");
//        sql.append("      WHEN '" + currentUserId + "' THEN 1 ");
//        sql.append("      ELSE 2 ");
//        sql.append("    END ");
//        sql.append("  WHEN '3' THEN ");
//        sql.append("    CASE CURRENT_AUDITOR_ID ");
//        sql.append("      WHEN '" + currentUserId + "' THEN 1 ");
//        sql.append("      ELSE 2 ");
//        sql.append("    END ");
//        sql.append("  WHEN '1' THEN 3 ");
//        sql.append("  WHEN '4' THEN 4 ");
//        sql.append("  WHEN '2' THEN 5 ");
//        sql.append("  WHEN '5' THEN 5 ");
//        sql.append("  WHEN '6' THEN 5 ");

        sql.append(" FROM T_APL_MONEY_MAIN ");
        sql.append(" WHERE 1 = 1 ");
        sql.append(condition);

        sql.append("  ORDER BY sortNo\n");
        //回款的排序
        if (!StringUtils.isBlank(haveRefund)) {
            sql.append(" ,refundSortNo,ESTIMATED_RETURN_DATE desc\n");
        }
        sql.append(" ,CREATE_TIME desc ");

        super.appendPageSql(sql, requestPage, pageSize);

        List<JSONObject> jsonList = super.queryForJsonList(sql.toString(), params);

        return jsonList;
    }

    public Integer copierReturn(String id, String copierReturnReason) {
        JSONObject obj = new JSONObject();
        obj.put("ID", id);
        obj.put("COPIER_RETURN_REASON", copierReturnReason);
        obj.put("AUDIT_FLAG", "2");
        obj.put("CURRENT_AUDITOR_ID", "");
        obj.put("CURRENT_AUDITOR_NAME", "");
        JSONObject objId = new JSONObject();
        objId.put("ID", id);
        return super.update("T_APL_MONEY_MAIN", obj, objId);
    }

    public Integer payReturn(String id, String payReturnUserId, String payReturnUserName, String payReturnReasonType, String payReturnReasonDesc) {
        JSONObject obj = new JSONObject();
        obj.put("ID", id);
        obj.put("PAY_RETURN_USER_ID", payReturnUserId);
        obj.put("PAY_RETURN_USER_NAME", payReturnUserName);
        obj.put("PAY_RETURN_REASON_TYPE", payReturnReasonType);
        obj.put("PAY_RETURN_REASON_DESC", payReturnReasonDesc);
        obj.put("AUDIT_FLAG", "5");
        JSONObject objId = new JSONObject();
        objId.put("ID", id);
        return super.update("T_APL_MONEY_MAIN", obj, objId);
    }

    public Integer getUnDoCount(String userId) {
        StringBuffer sql = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<>();
        sql.append(" SELECT COUNT(1) AS count FROM " + iBaseEntity.getTableName() + " WHERE CURRENT_AUDITOR_ID = ? AND AUDIT_FLAG IN ('0','3')");
        sqlArgs.add(userId);
        String count = super.queryForString(sql.toString(), sqlArgs.toArray());
        return Integer.parseInt(count);
    }

    @Override
    public Integer update(IBaseEntity entity) {
        entity.setUpdateTime(super.getCurrentTime());
        logsDao.saveLogs(entity);
        return super.update(entity.getTableName(), entity.getJSONObject(), entity.getJSONObjectId());
    }

    @Override
    public Integer add(IBaseEntity entity) {
        entity.setId(super.generateKey());
        entity.setCreateTime(super.getCurrentTime());
        entity.setUpdateTime(super.getCurrentTime());
        logsDao.addLogs(entity);
        return super.insert(entity.getTableName(), entity.getJSONObject());
    }
}
